﻿using Caching;
using SmallJob.Model;
using SmallJob.Services.Code;
using SmallJob.Services.Interfaces;
using SmallShop.Services.Implements;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;

namespace FrontEnd.Controllers
{
    public class ProvideController : Controller
    {
        //
        // GET: /Provide/
        private readonly IProvideService _ProvideService;

        private readonly ICategoryService _CategoryService;
        private readonly IUserService _UserService;
        private readonly IProvideCommentService _ProvideCommentService;
        private readonly IOrderService _OrderService;
        private readonly IFollowerService _FollowerService;

        public ProvideController(IProvideService providerService, ICategoryService CategoryService, IUserService UserService, IProvideCommentService ProvideCommentService, IOrderService OrderService, IFollowerService FollowerService)
        {
            _CategoryService = CategoryService;
            _ProvideService = providerService;
            _UserService = UserService;
            _ProvideCommentService = ProvideCommentService;
            _OrderService = OrderService;
            _FollowerService = FollowerService;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Add()
        {
            if (!User.Identity.IsAuthenticated)
                return RedirectToAction("index", "home");
            int id = 0;
            var u = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
            try
            {
                id = Convert.ToInt32(RouteData.Values["id"]);
            }
            catch
            {
                id = 0;
            }
            var request = _ProvideService.GetById(id);
            if (request == null)
            {
                request = new Provide()
                {
                    ID = 0,
                    DescriptionOrder = "",
                    DescriptionPay = "",
                    Price = 0,
                    Title = "",
                    Location = ""
                };
            }
            else
            {
                if (request.UserID != u.ID)
                {
                    return RedirectToAction("index", "home");
                }
            }
            List<Category> listCate = null;
            if (MemCache.Get<List<Category>>("category") == null)
            {
                listCate = _CategoryService.GetAllAvaiable();
                MemCache.InsertCache("category", listCate);
            }
            else
            {
                listCate = MemCache.Get<List<Category>>("category");
            }
            ViewData["AllCate"] = listCate;
            return View(request);
        }

        [ValidateInput(false)]
        public ActionResult Save(IEnumerable<HttpPostedFileBase> imgs, HttpPostedFileBase file, List<String> oldImg, string description)
        {
            if (!User.Identity.IsAuthenticated)
                return RedirectToAction("index", "Home");
            int id = Convert.ToInt32(Request.Form["id"]);
            var provide = _ProvideService.GetById(id);
            if (provide == null)
                provide = new Provide()
                {
                    ID = 0,
                    CreatedDate = DateTime.Now,
                    Price = 0
                };
            provide.Title = Request.Form["title"];
            provide.Location = Request.Form["location"];
            provide.CategoryID = Convert.ToInt32(Request.Form["cateID"]);
            provide.DescriptionOrder = HttpUtility.HtmlEncode(description);
            provide.DescriptionPay = "";
            //provide.DescriptionPay = Request.Form["DesPay"];
            provide.ModifiedDate = DateTime.Now;
            var u = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
            provide.UserID = u.ID;
            provide.SkillID = Convert.ToInt32(Request.Form["skillID"]);
            try
            {
                provide.Price = Convert.ToInt32(Request.Form["price"]) * 1000;
            }
            catch
            {
                ModelState.AddModelError("PriceInvalid", "Nhập Đúng Giá");
            }
            try
            {
                provide.TimeToComplete = Convert.ToInt32(Request.Form["complete"]);
            }
            catch
            {
                ModelState.AddModelError("Time Complete Invalid", "Thời gian để hoàn thành, nhập số nguyên theo ngày.");
            }
            if (string.IsNullOrWhiteSpace(provide.Title))
                ModelState.AddModelError("TitleInvalid", "Tiêu đề không được bỏ trống.");
            else if (provide.Title.Length > 50)
                ModelState.AddModelError("TitleInvalid", "Tiêu đề không nên dài quá 50 ký tự.");
            if (string.IsNullOrWhiteSpace(provide.Location))
                ModelState.AddModelError("LocationInvalid", "Địa điểm không được bỏ trống.");
            if (string.IsNullOrWhiteSpace(provide.DescriptionOrder))
                ModelState.AddModelError("DescriptionOrderInvalid", "Nội dung không được bỏ trống.");
            provide.ImagePath = "";
            //upload delivery
            if (file != null && file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                fileName = UploadHelper.GetNamePlusDatetime(fileName, true);
                var path = Path.Combine(UploadHelper.GetPathSaveFile(u.ID), fileName);
                if (file.ContentLength > (1024 * 1024 * 200))
                {
                    ModelState.AddModelError("FileInvalid", "Dung lượng của tập tin vượt quá cho phép.");
                }
                else
                {
                    file.SaveAs(path);
                    provide.IsDeliveryImmediate = true;
                    provide.Download = fileName;
                }
            }
            if (provide != null)
            {
                if (Request.Form["deliveryimmediate"] != null)
                {
                    provide.IsDeliveryImmediate = true;
                }
                else
                {
                    provide.IsDeliveryImmediate = false;
                }
            }

            if (oldImg != null)
            {
                foreach (var item in oldImg)
                {
                    provide.ImagePath += item + ";";
                }
            }
            if (imgs != null && imgs.Count() != 0)
            {
                var total = imgs.Count();
                var count = 0;
                foreach (var img in imgs)
                {
                    if (img != null && img.ContentLength != 0)
                    {
                        DateTime dt = DateTime.Now;
                        // extract only the fielname

                        var fileName = Path.GetFileName(img.FileName);
                        Regex regex = new Regex(Resources.Resource.RegexRemoveCharacter);
                        fileName = regex.Replace(fileName, "");
                        // upload anh vao folder
                        var path = Path.Combine(UserUtility.GetFolderProvideUpload() + u.ID, dt.ToBinary() + "_" + fileName);
                        if (!Directory.Exists(UserUtility.GetFolderProvideUpload() + u.ID))
                        {
                            Directory.CreateDirectory(UserUtility.GetFolderProvideUpload() + u.ID);
                        }
                        img.SaveAs(path);

                        WebImage webimg = new WebImage(path);
                        var validsize = true;
                        if (webimg.Width < 600)
                        {
                            validsize = false;
                        }
                        else if (webimg.Height < 400)
                        {
                            validsize = false;
                        }
                        if (validsize)
                        {
                            provide.ImagePath += UserUtility.GetImageProvideUpload() + u.ID + "/" + dt.ToBinary() + "_" + fileName + ";";
                        }
                        else
                        {
                            count++;
                        }
                    }
                }
                if (count == total)
                {
                    ModelState.AddModelError("Imageerrors", "Cần có ít nhất một hình ảnh đúng kích cỡ 600x400.");
                }
                else if (count > 0)
                {
                    TempData["warnings"] = "Một số hình ảnh của bạn sai kích cỡ sẽ không được lưu.";
                }
            }
            else if (oldImg == null || oldImg.Count == 0)
            {
                ModelState.AddModelError("Imageerrors", "Cần có ít nhất một hình ảnh và kích cỡ 600x400.");
            }
            //image

            if (ModelState.IsValid)
            {
                if (provide.ID == 0)
                {
                    _ProvideService.Add(provide);
                    TempData["mess"] = "Thêm thành công!";
                    TempData["pID"] = provide.ID;
                    provide.User = _UserService.GetById(provide.UserID);
                    MemCache.InsertCache("provide_" + provide.ID, provide);
                    return RedirectToAction("Add");
                }
                else
                {
                    _ProvideService.Update(provide);
                    TempData["mess"] = "Sửa thành công!";
                    TempData["pID"] = provide.ID;
                    provide.User = _UserService.GetById(provide.UserID);
                    MemCache.InsertCache("provide_" + provide.ID, provide);
                    return new RedirectResult("/sua-dich-vu/" + provide.ID);
                }
            }
            List<Category> listCate = null;
            if (MemCache.Get<List<Category>>("category") == null)
            {
                listCate = _CategoryService.GetAllAvaiable();
                MemCache.InsertCache("category", listCate);
            }
            else
            {
                listCate = MemCache.Get<List<Category>>("category");
            }
            ViewData["AllCate"] = listCate;
            TempData["errors"] = ModelState;
            return View("Add", provide);
        }

        public ActionResult Details()
        {
            int id = 0;
            try
            {
                id = Convert.ToInt16(RouteData.Values["id"]);
            }
            catch
            {
                return RedirectToAction("Error404", "Error");
            }
            Provide provide = null;
            if (MemCache.Get<Provide>("provide_" + id) == null)
            {
                provide = _ProvideService.GetById(id);
                if (provide == null)
                {
                    RedirectToAction("index", "home");
                }
                provide.User = _UserService.GetById(provide.UserID);
                MemCache.InsertCache("provide_" + provide.ID, provide);
            }
            else
            {
                provide = MemCache.Get<Provide>("provide_" + id);
            }
            var u = _UserService.GetByFBID(User.Identity.Name) ?? _UserService.GetByEmail(User.Identity.Name);
            ViewData["isOwner"] = (u == null ? false : u.ID == provide.User.ID);
            var orders = _OrderService.GetOrderComment(provide.ID);
            foreach (var item in orders)
            {
                item.Buyer = _UserService.GetById(item.BuyerID);
            }
            ViewData["comment"] = orders;
            ViewData["isFollowwed"] = false;
            if (u != null)
            {
                if (_FollowerService.IsExist(u.ID, provide.User.ID))
                {
                    ViewData["isFollowwed"] = !_FollowerService.GetByID(u.ID, provide.User.ID).IsDeleted;
                }
            }
            if (TempData["issuccess"] != null)
            {
                ViewData["issuccess"] = TempData["issuccess"];
                ViewData["orderid"] = TempData["orderid"];
                if (!Convert.ToBoolean(TempData["issuccess"]))
                {
                    ViewData["result"] = TempData["result"];
                }
            }
            return View(provide);
        }

        public ActionResult Category(string id, string name)
        {
            int intid = 1;
            try
            {
                intid = Convert.ToInt32(id);
            }
            catch (Exception)
            {
            }

            if (!string.IsNullOrWhiteSpace(id))
            {
                var category = _CategoryService.GetById(intid);
                if (category == null)
                {
                    category = _CategoryService.GetAllAvaiable().First();
                }
                var lst = _ProvideService.GetProvideByCategoryID(intid);
                foreach (var item in lst)
                {
                    item.User = _UserService.GetById(item.UserID);
                }

                ViewData["provides"] = lst;
                ViewData["listtitle"] = category.Name;
                ViewData["selectcate"] = category.ID;
            }
            List<Category> listCate = null;
            if (MemCache.Get<List<Category>>("category") == null)
            {
                listCate = _CategoryService.GetAllAvaiable();
                MemCache.InsertCache("category", listCate);
            }
            else
            {
                listCate = MemCache.Get<List<Category>>("category");
            }
            ViewData["AllCate"] = listCate;
            return View("Show");
        }

        public ActionResult Location(string id)
        {
            int intid = 1;
            try
            {
                intid = Convert.ToInt32(id);
            }
            catch (Exception)
            {
            }
            var location = (from c in UtilityService.GetCities()
                            where c.ID == intid
                            select c).SingleOrDefault();
            if (location == null)
            {
                location = UtilityService.GetCities().First();
            }
            var lst = _ProvideService.GetByLocation(location.Name);
            foreach (var item in lst)
            {
                item.User = _UserService.GetById(item.UserID);
            }
            List<Category> listCate = null;
            if (MemCache.Get<List<Category>>("category") == null)
            {
                listCate = _CategoryService.GetAllAvaiable();
                MemCache.InsertCache("category", listCate);
            }
            else
            {
                listCate = MemCache.Get<List<Category>>("category");
            }
            ViewData["AllCate"] = listCate;
            ViewData["provides"] = lst;
            ViewData["listtitle"] = location.Name;
            ViewData["selectlocal"] = location.Name;
            return View("Show");
        }

        public ActionResult Search(string search)
        {
            var listPro = _ProvideService.Find(search);
            foreach (var item in listPro)
            {
                item.User = _UserService.GetById(item.UserID);
            }
            List<Category> listCate = null;
            if (MemCache.Get<List<Category>>("category") == null)
            {
                listCate = _CategoryService.GetAllAvaiable();
                MemCache.InsertCache("category", listCate);
            }
            else
            {
                listCate = MemCache.Get<List<Category>>("category");
            }
            ViewData["AllCate"] = listCate;
            ViewData["provides"] = listPro;
            ViewData["listtitle"] = "Kết quả tìm kiếm của: " + search;
            ViewData["selectfilter"] = search;
            return View("show");
        }

        public ActionResult Show(string page)
        {
            var location = Request.QueryString["paramlocation"];
            var category = Request.QueryString["paramcategory"];
            var title = Request.QueryString["paramtitle"];
            var minprice = Request.QueryString["minprice"];
            var maxprice = Request.QueryString["maxprice"];

            var listPro = new List<Provide>();
            if (string.IsNullOrWhiteSpace(location) && string.IsNullOrWhiteSpace(category) && string.IsNullOrWhiteSpace(title) && string.IsNullOrWhiteSpace(minprice) && string.IsNullOrWhiteSpace(maxprice))
            {
                listPro = _ProvideService.GetAllProvide();
            }
            else
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(minprice)) minprice = "-1";
                    if (string.IsNullOrWhiteSpace(maxprice)) maxprice = "-1";
                    var intminprice = Convert.ToInt32(minprice);
                    var intmaxprice = Convert.ToInt32(maxprice);
                    var categoryid = (string.IsNullOrWhiteSpace(category) ? 0 : Convert.ToInt32(category));
                    listPro = _ProvideService.Filter(location, categoryid, title, intminprice, intmaxprice);
                }
                catch (Exception)
                {

                    return Json(false);
                }
            }
            foreach (var item in listPro)
            {
                item.User = _UserService.GetById(item.UserID);
            }
            List<Category> listCate = null;
            if (MemCache.Get<List<Category>>("category") == null)
            {
                listCate = _CategoryService.GetAllAvaiable();
                MemCache.InsertCache("category", listCate);
            }
            else
            {
                listCate = MemCache.Get<List<Category>>("category");
            }
            ViewData["AllCate"] = listCate;
            ViewData["provides"] = listPro;
            ViewData["listtitle"] = "Tìm kiếm";
            return View();
        }
    }
}